package cn.kgc.ssm.controller;

import cn.hutool.captcha.LineCaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 课工场
 * @date 2024/5/13
 * @description 验证码请求
 */
@Controller
public class CaptchaController {

    // 生成验证码
    @RequestMapping(value = "captcha", method = RequestMethod.GET)
    public void createCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 生成验证码图片  保存验证码
        LineCaptcha lineCaptcha = new LineCaptcha(100, 40, 4, 4);
        String code = lineCaptcha.getCode();
        System.out.println("code = " + code);
        // session -> cookie     request    application   code： 1234
        HttpSession session = request.getSession();
        session.setAttribute("code", code);
        // 将图片以流的形式写出到前端
        ServletOutputStream outputStream = response.getOutputStream();
        lineCaptcha.write(outputStream);
        outputStream.close();

    }
}
